package pers.jason.wppm.edge.system.security.userdetails;

import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Service;

import pers.jason.wppm.api.entity.auth.Role;
import pers.jason.wppm.api.entity.auth.User;
import pers.jason.wppm.api.support.ResultView;
import pers.jason.wppm.auth.api.UserApi;
import pers.jason.wppm.auth.api.enums.LoginType;

import java.util.Set;

/**
 * 
 * @author Jason
 * @Date 2018-10-29 11:03
 *
 */
@Service
@Log4j
public class DefaultJdbcUserDetails implements UserDetailsService, SocialUserDetailsService {

	@Autowired
	private UserApi userApi;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		ResultView resultView = userApi.getUserByLoginName(LoginType.LOGIN_BY_FORM.getName(), null, null, username);
		if(null == resultView || !"success".equals(resultView.getResult())) {
			throw new RuntimeException("获取用户信息失败");
		}
		String jsonStr = JSON.toJSONString(resultView.getObj());
		User user = JSON.parseObject(jsonStr, User.class);
		StringBuilder roles = new StringBuilder();
		String roleStr = "";
		Set<Role> roleSet = user.getRoles();
		if(null != roleSet && roleSet.size() > 0) {
			for(Role role : roleSet) {
				roles.append("," + role.getName());
			}
			roleStr = StringUtils.substring(roles.toString(), 1);
		}
		return new UserDetailsInfo(user, roleStr);
		//return new org.springframework.security.core.userdetails.User(username, user.getPassword(), user.getEnable(), user.getAccountNonExpired(), user.getCredentialsNonExpired(), user.getAccountNonLocked(), AuthorityUtils.commaSeparatedStringToAuthorityList(roleStr));
	}

	@Override
	public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
		return null;
	}
}
